import 'package:calf_account/database/crud.dart';
import 'package:calf_account/model/pass_tag.dart';
import 'package:calf_account/model/password.dart';
import 'package:calf_account/model/result.dart';
import 'package:dio/dio.dart';

class PasswordApi {
  static const String _domain = "https://so.iqiyi.com/so/";
  static const String _passUrl = "";
  static const String _tagsUrl = "";

  ///加载密码数据
  static Future<List<Password>> loadPasswords(
      Iterable<int> tagIds, String key) async {
    Response r = await Dio(BaseOptions(baseUrl: _domain)).get(
      _passUrl,
      queryParameters: {
        "tagIds": tagIds,
        "key": key,
      },
    );

    if (r.statusCode == 200) {
      return r.data;
    } else {
      throw Exception(r.statusMessage);
    }
  }

  ///加载密码数据
  static Future<List<PasswordTag>> loadTags() async {
    Response r = await Dio(BaseOptions(baseUrl: _domain)).get(
      _tagsUrl,
      queryParameters: {},
    );

    if (r.statusCode == 200) {
      return r.data;
    } else {
      throw Exception(r.statusMessage);
    }
  }

  ///保存密码数据
  static Future<List<PasswordTag>> savePassword(Password password) async {
    Response r = await Dio(BaseOptions(baseUrl: _domain)).post(
      _tagsUrl,
      data: password,
    );

    if (r.statusCode == 200) {
      return r.data;
    } else {
      throw Exception(r.statusMessage);
    }
  }

  ///-----------------------------Local Save------------------------------------

  ///加载密码数据
  static Future<List<Password>> localLoadPasswords(
      Iterable<int> tagIds, String key) async {
    return CRUD.queryPasswords(tagIds, key);
  }

  ///加载标签数据
  static Future<List<PasswordTag>> localLoadTags() async {
    return CRUD.queryTags();
  }

  ///保存密码数据
  static Future<Result> localSavePassword(Password password) async {
    if (password.id == null) {
      CRUD.insertPassword(password);
      return Result();
    } else {
      CRUD.updatePassword(password);
      return Result();
    }
  }

  ///保存标签数据
  static Future<Result> localSaveTag(PasswordTag tag) async {
    if (tag.id == null) {
      CRUD.insertPassTag(tag);
      return Result();
    } else {
      CRUD.updatePassTag(tag);
      return Result();
    }
  }
}
